import json

import execjs
import requests as req

from codes.commons.configs import easiest_common_headers as common_headers
from codes.commons.common_utils import get_seconds_stamp

with open('../../resources/match2/index_script_break.js', 'r', encoding='utf8') as f:
    js_ctx = execjs.compile(f.read())


def get_stamp_encrypted(stamp):
    return js_ctx.call('U', stamp)


def request_pages():
    num_total = 0
    for i in range(5):
        page_content = request_html_by_pages(i + 1)
        print(f'获取第【{i + 1}】页数据：{page_content}')
        con_obj = json.loads(page_content)
        for d in con_obj['data']:
            num_total += d['value']
    print('合计为: ', num_total)


def request_html_by_pages(page: int):
    url = 'http://match.yuanrenxue.com/api/match/2?page=' + str(page)
    seconds_stamp = get_seconds_stamp()
    stamp_encrypted = get_stamp_encrypted(seconds_stamp)
    cookies = {
        'm': stamp_encrypted + '|' + str(seconds_stamp)
    }
    resp = req.get(url=url, headers=common_headers, cookies=cookies)
    if 200 == resp.status_code:
        return resp.text
    else:
        print(f'其他状态码:{resp.status_code}, 页面: {resp.text}')
        return None


if __name__ == '__main__':
    request_pages()
